import {
  publisherPermissions
} from "../../utils/permission-sdk";

module.exports = Behavior({
  data: {
    skinClass: '', //主题样式
    needLogin: true, //是否需要登录,默认需要登录
    logined: false, //是否登录
  },

  pageLifetimes: {
    show: async function () {
      const {
        needLogin,
        psconfig,
      } = this.data;
      const app = getApp();
      let {
        logined,
        skinClass
      } = app.globalData;

      // 登录
      if (needLogin) {
        if (!logined) {
          await app.init();
          // 再次获取登录状态
          let { logined: logined2 } = app.globalData;
          logined = logined2;
        }
      }

      // 权限
      const menu = wx.getStorageSync('menu');
      let d = {};
      if (psconfig) {
        const { page, btns } = psconfig;

        // 页面权限
        if (page) {
          const { menuId, permissions = 0 } = page;
          const menuPermissions = this.getPermissions(menuId, menu);

          if (!((menuPermissions & permissions) > 0)) {
            wx.showModal({
              title: '提示',
              content: '你暂无权限访问该页面！',
              showCancel: false,
              success: (r) => {
                if (r.confirm) {
                  wx.navigateBack();
                }
              }
            });
            return;
          }
        }

        // 页面中按钮的权限
        if (btns) {
          btns.forEach(i => {
            const { menuId, name } = i;
            const menuPermissions = this.getPermissions(menuId, menu);
            const btn = this.data[name];
            d[name] = btn.filter?.(j => !j.permissions || (menuPermissions & j.permissions) > 0)
          });
        }
      }

      publisherPermissions.emit('permissions');
      this.setData({
        app,
        skinClass,
        logined,
        ...d,
      });
    },
  },
  methods: {
    getPermissions(mId, m) {
      let p = 0;

      m.some(i => {
        if (i.id === mId) {
          p = i.permissions;
        }
        else if (i.children) {
          p = this.getPermissions(mId, i.children);
        }

        if (p > 0) {
          return true;
        }
      })

      return p;
    }
  }
})